package sunwin.yois.web.controller;

import jodd.datetime.JDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sunwin.yois.web.common.R;
import sunwin.yois.web.common.YoisControllerDefaultData;
import sunwin.yois.web.model.WeatherDomain;
import sunwin.yois.web.model.WeatherNoticeDomain;
import sunwin.yois.web.uiservice.WeatherService;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.domain.publicty.NewsDomain;
import sunwin.yoms.domain.publicty.VideoDomain;
import sunwin.yoms.domain.resource.StadiumDomain;
import sunwin.yoms.service.publicty.NewsService;
import sunwin.yoms.service.publicty.VideoService;
import sunwin.yoms.service.resource.StadiumService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liangzizheng on 2015/8/24.
 */
@Controller
public class IndexController {
    @Autowired
    private NewsService newsService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private StadiumService stadiumService;
    @Autowired
    private YoisControllerDefaultData defaultData;

    @RequestMapping(value = R.IsLogin, method = RequestMethod.GET, produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public String IsLogin(String url) {
        if(defaultData.getCurrentYimsUserDetails() != null){
            return "<html><script>var token='isLogin';window.location.href='" + url + "';</script></html>";
        } else {
            return "success";
        }
    }

    /**
     * 百度站内搜索key
     *
     * @return
     */
    @RequestMapping(value = R.Baidu, method = RequestMethod.GET, produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public Object baiduSearchKey() {
        return "8GoRkL14bh";
    }

    /**
     * 访问登录页面
     *
     * @return
     */
    @RequestMapping(value = R.Login, method = RequestMethod.GET)
    public String login() {
        return "user/login";
    }

    /**
     * 搜索页面
     *
     * @return
     */
    @RequestMapping(value = R.Seach, method = RequestMethod.GET)
    public String seach(ModelMap map, String q) {
        map.addAttribute("key", q);
        return "seach";
    }

    /**
     * 登录失败时返回login.vm。区别在于给modelmap中加入了错误消息
     *
     * @param map
     * @return
     */
    @RequestMapping(value = R.LoginError, method = RequestMethod.GET)
    public String loginError(ModelMap map) {
        map.addAttribute("error", "登录失败，请检查用户密码是否正确");
        return "user/login";
    }

    /**
     * 403错误
     *
     * @return
     */
    @RequestMapping(value = "403", method = RequestMethod.GET)
    public String error403() {
        return "error/403";
    }

    /**
     * 404错误
     *
     * @return
     */
    @RequestMapping(value = "404", method = RequestMethod.GET)
    public String error404() {
        return "error/404";
    }

    /**
     * 访问首页
     *
     * @param modelMap
     * @throws YomsException
     */
    @RequestMapping(value = R.Index, method = RequestMethod.GET)
    public void Index(ModelMap modelMap) throws YomsException, IOException {
        getFlashs(modelMap);
        getNotices(modelMap);
        getMetroImg(modelMap);
        getEvents(modelMap);
        getWeather(modelMap);
        getHotStadium(modelMap);
        getFingerpostSport(modelMap);
        getVideos(modelMap);

        //contractionImage.resetsize("D:\\1.jpeg", "D:\\1.jpeg");
    }

    /**
     * 获取8条快讯，其中最新的快讯为头条快讯
     * 当数据库数据为空时添加一个model告知客户端没有最新的信息
     */
    private void getFlashs(ModelMap modelMap) {
        List<NewsDomain> newsFlashs = new ArrayList<>();

        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageSize(8);
        yomsPage.setPageIndex(1);

        newsFlashs = newsService.getNewsByTypeId(1, yomsPage);

        if (newsFlashs.size() == 0) {
            NewsDomain newsDomain = new NewsDomain();
            newsDomain.setNewsTitle("公园暂时没有快讯信息");
            newsFlashs.add(newsDomain);
            modelMap.addAttribute("newsFlashTop", newsDomain);
        } else {
            NewsDomain flashTop = newsFlashs.get(0);
            if (newsFlashs.size() > 0) {
                newsFlashs.remove(0);
            }
            modelMap.addAttribute("newsFlashTop", flashTop);
            modelMap.addAttribute("newsFlashs", newsFlashs);
        }
    }

    /**
     * 获取8条公告，其中最新的公告为头条公告
     * 当数据库数据为空时添加一个model告知客户端没有最新的信息
     */
    private void getNotices(ModelMap modelMap) {
        List<NewsDomain> newsNotices = new ArrayList<>();

        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageSize(8);
        yomsPage.setPageIndex(1);

        newsNotices = newsService.getNewsByTypeId(2, yomsPage);

        if (newsNotices.size() == 0) {
            NewsDomain newsDomain = new NewsDomain();
            newsDomain.setNewsTitle("公园暂时没有公告信息");
            newsNotices.add(newsDomain);
            modelMap.addAttribute("newsNoticeTop", newsDomain);
        } else {
            NewsDomain noticeTop = newsNotices.get(0);
            if (newsNotices.size() > 0) {
                newsNotices.remove(0);
            }
            modelMap.addAttribute("newsNoticeTop", noticeTop);
            modelMap.addAttribute("newsNotices", newsNotices);
        }
    }

    /**
     * 获取3条电影，分别是最新添加的公告，快讯，赛事，场馆
     * 其中公告和快讯二选一，如果没有公告时获取快讯
     * 当其中一种信息为空时模拟一个Model告知客户端
     */
    private void getMetroImg(ModelMap modelMap) {
        List<NewsDomain> domains = new ArrayList<>();

        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageSize(8);
        yomsPage.setPageIndex(1);

        NewsDomain uptodateNotice = newsService.getUptodateNotice();
        if (uptodateNotice != null) {
            uptodateNotice.setNewsImg(R.YomUrl + "/" + uptodateNotice.getNewsImg());
            modelMap.addAttribute("uptodateNotice", uptodateNotice);
        } else {
            NewsDomain uptodateFlash = newsService.getUptodateFlash();
            if (uptodateFlash != null) {
                uptodateFlash.setNewsImg(R.YomUrl + "/" + uptodateFlash.getNewsImg());
                modelMap.addAttribute("uptodateNotice", uptodateFlash);
            } else {
                modelMap.addAttribute("uptodateNotice", getDefaultNews());
            }
        }

        NewsDomain uptodateEvents = newsService.getUptodateEvents();
        if (uptodateEvents != null) {
            uptodateEvents.setNewsImg(R.YomUrl + "/" + uptodateEvents.getNewsImg());
            modelMap.addAttribute("uptodateEvents", uptodateEvents);
        } else {
            modelMap.addAttribute("uptodateEvents", getDefaultNews());
        }

        StadiumDomain hottestStatium = stadiumService.getHottestStadium();
        if (hottestStatium != null) {
            hottestStatium.setStadiumImg(R.YomUrl + "/" + hottestStatium.getStadiumImg());
            modelMap.addAttribute("hottestStatium", hottestStatium);
        } else {
            modelMap.addAttribute("hottestStatium", getDefaultStadium());
        }
    }

    /**
     * 获取空场馆
     *
     * @return
     */
    private StadiumDomain getDefaultStadium() {
        StadiumDomain defaultStadium = new StadiumDomain();
        defaultStadium.setStadiumImg("/img/default/default-carousel.jpg");
        defaultStadium.setStadiumName("&nbsp;");

        return defaultStadium;
    }

    /**
     * 获取空新闻
     *
     * @return
     */
    private NewsDomain getDefaultNews() {
        NewsDomain defaultNews = new NewsDomain();
        defaultNews.setNewsImg("/img/default/default-carousel.jpg");
        defaultNews.setNewsTitle("&nbsp;");

        return defaultNews;
    }

    /**
     * 获取赛事
     *
     * @param modelMap
     */
    private void getEvents(ModelMap modelMap) {
        JDateTime today1 = new JDateTime();
        JDateTime today2 = new JDateTime();
        JDateTime today3 = new JDateTime();
        JDateTime today4 = new JDateTime();

        today1.setTime(0, 0, 0, 0);
        today2.setTime(0, 0, 0, 0);
        today3.setTime(0, 0, 0, 0);
        today4.setTime(0, 0, 0, 0);

        int pageSize = 7;

        List<NewsDomain> todayNews = newsService.getTodayEvents(today1, pageSize);
        if (todayNews.size() == 0) {
            todayNews.add(getDefaultEventsNews());
        }
        modelMap.addAttribute("todayNews", todayNews);

        List<NewsDomain> tomorrowNews = newsService.getTodayEvents(today2.addDay(1), pageSize);
        if (tomorrowNews.size() == 0) {
            tomorrowNews.add(getDefaultEventsNews());
        }
        modelMap.addAttribute("tomorrowNews", tomorrowNews);

        List<NewsDomain> afterNews = newsService.getTodayEvents(today3.addDay(2), pageSize);
        if (afterNews.size() == 0) {
            afterNews.add(getDefaultEventsNews());
        }
        modelMap.addAttribute("afterNews", afterNews);

        List<NewsDomain> moreNews = newsService.getTodayEvents(today4.addDay(3), pageSize);
        if (moreNews.size() == 0) {
            moreNews.add(getDefaultEventsNews());
        }
        modelMap.addAttribute("moreNews", moreNews);
    }

    /**
     * 获取默认赛事
     *
     * @return
     */
    private NewsDomain getDefaultEventsNews() {
        NewsDomain defaultNews = new NewsDomain();
        defaultNews.setNewsTitle("暂无赛事");

        return defaultNews;
    }

    /**
     * 天气
     *
     * @param modelMap
     */
    private void getWeather(ModelMap modelMap) {
        try {
            String cityName = R.Address;
            WeatherDomain weatherDomain = WeatherService.Instance.getWeatherInformation(cityName);
            modelMap.addAttribute("weather", weatherDomain);
            modelMap.addAttribute("todayWeather", weatherDomain.getWeatherDateDomains().get(1));
            modelMap.addAttribute("tomorrowWeather", weatherDomain.getWeatherDateDomains().get(2));
            modelMap.addAttribute("afterDayWeather", weatherDomain.getWeatherDateDomains().get(3));
            for (WeatherNoticeDomain item : weatherDomain.getWeatherNotices()) {
                if (item.getName().equals("运动指数")) {
                    modelMap.addAttribute("exersize", item);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取热门场馆
     *
     * @param modelMap
     */
    private void getHotStadium(ModelMap modelMap) {
        List<StadiumDomain> hotStadiums = stadiumService.findStadiumHot(8);
        modelMap.addAttribute("hotStadiums", hotStadiums);
    }

    /**
     * 获取健身指南
     *
     * @param modelMap
     */
    private void getFingerpostSport(ModelMap modelMap) {
        List<NewsDomain> domains = newsService.getSportFingerpost(8);
        modelMap.addAttribute("fingerpostSports", domains);
    }

    /**
     * 获取健身健身培训
     *
     * @param modelMap
     */
    private void getTrainSport(ModelMap modelMap) {
        List<NewsDomain> domains = newsService.getSportCultivate(8);
        modelMap.addAttribute("trainSports", domains);
    }

    /**
     * 获取视频
     *
     * @param modelMap
     */
    private void getVideos(ModelMap modelMap) {
        YomsPage yomsPage = new YomsPage();
        yomsPage.setPageIndex(1);
        yomsPage.setPageSize(1);

        //获取第一个视频
        List<VideoDomain> tempVideos = videoService.getVideoOrderByHot(yomsPage);
        VideoDomain videoDomain = null;
        if (tempVideos.size() == 1) {
            videoDomain = tempVideos.get(0);
        } else {
            videoDomain = new VideoDomain();
            videoDomain.setVideoName("...");
        }
        modelMap.addAttribute("firstVideo", videoDomain);

        //获取视频2，3，4
        yomsPage.setPageSize(5);
        tempVideos = videoService.getVideoOrderByHot(yomsPage);
        if (tempVideos.size() > 0) {
            tempVideos.remove(0);
        }

        modelMap.addAttribute("videos", tempVideos);
    }
}
